package com.summer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.common.OperateThreadLocal;
import com.summer.entity.*;
import com.summer.mapper.OrdersMapper;
import com.summer.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Transactional
    @Override
    public void orderMealSubmit(Orders orders) {
        //0. 数据准备
        Long userId = OperateThreadLocal.getLocalThreadAttribute();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);
        User user = userService.getById(userId);
        //根据传过来的地址id查询地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        long orderNumber = IdWorker.getId(); // TODO IdWorker可生成id 订单号

        //2. 添加订单明细表, 顺便计算总金额
        AtomicInteger amount = new AtomicInteger(0); //TODO 保证高并发时不会有误差代替int amount = 0;
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCartOne : shoppingCartList) {
            // 创建订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            //set订单id
            orderDetail.setOrderId(orderNumber);
            //set名称
            orderDetail.setName(shoppingCartOne.getName());
            //set菜品id
            orderDetail.setDishId(shoppingCartOne.getDishId());
            //set套餐id
            orderDetail.setSetmealId(shoppingCartOne.getSetmealId());
            //set口味
            orderDetail.setDishFlavor(shoppingCartOne.getDishFlavor());
            //set数量
            orderDetail.setNumber(shoppingCartOne.getNumber());
            //set金额
            orderDetail.setAmount(shoppingCartOne.getAmount());
            //set图片
            orderDetail.setImage(shoppingCartOne.getImage());
            //添加到列表
            orderDetailList.add(orderDetail);
            //TODO 保证高并发时计算不会出错相当于amount += shoppingCartOne.getAmount()* new BigDecimal(shoppingCartOne.getNumber());
            amount.addAndGet(shoppingCartOne.getAmount().multiply(new BigDecimal(shoppingCartOne.getNumber())).intValue());
        }
        orderDetailService.saveBatch(orderDetailList);

        //2. 添加订单表
        //set订单号
        orders.setNumber(String.valueOf(orderNumber));
        //set下单时间
        orders.setOrderTime(LocalDateTime.now());
        //set结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //set实收金额
        orders.setAmount(new BigDecimal(amount.get()));
        //set用户名 这里值user中的用户名
        orders.setUserName(user.getName());
        //用户id
        orders.setUserId(user.getId());
        //set手机号, 这里指地址簿中的电话号码
        orders.setPhone(addressBook.getPhone());
        //set地址
        String address = (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())+
                (addressBook.getCityName() == null ? "" : addressBook.getCityName())+
                (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())+
                (addressBook.getDetail() == null ? "" : addressBook.getDetail());
        orders.setAddress(address);
        //set收货人
        orders.setConsignee(addressBook.getConsignee());
        this.save(orders);


            //3. 删除购物车
        shoppingCartService.remove(lqw);
            //4. 事务处理、异常处理

    }
}
